import { Button, ConfigProvider, DatePicker, Input, message, Popover, Select, Table, Tooltip, Upload, UploadProps } from "antd";
import { DataDetailBox } from "../../style";
import { useCallback, useEffect, useState } from "react";
import { ColumnsType } from "antd/es/table";
import { basicIp } from "../../../../../api/http";
import { IshipDetailType, postShipDetail } from "../../api";
import { gethandleTemplateDownload } from "../../../../../assets/fun/fileDownloadFun";
import { ImportOutlined, PlusOutlined, ExportOutlined, DeliveredProcedureOutlined, SettingOutlined } from '@ant-design/icons'
import AddInfo from "../AddInfo";
import axios from "axios";
import { TablePaginationPosition } from "../../../../../type/antd";
import { useWindowFontSize } from "../../../../../assets/fun/Antd/configprovider";
import { IFenye } from "../../../../../type/commit";
import { ShengDiv, ShengTanchaung } from "../../../../../assets/style/ShengTanchaung";
import { licensePlateAbbreviations } from "../../../../../assets/data";
import dayjs from "dayjs";
import DaochuSetModule from '../DaochuSetModule'

const { RangePicker } = DatePicker;

const DataDetail = () => {
    const [addShow, setAddShow] = useState(false);
    const [prefix, setPrefix] = useState('黄'); // 存储车牌前缀的状态
    const [searchValue, setSearchValue] = useState(''); // 存储搜索框的值
    const [listData, setListData] = useState<IshipDetailType[]>([]); //列表数据
    const [totalValue, settotalValue] = useState(0); //总条数
    const [mobanxiazaiLoading, setMobanxiazaiLoading] = useState(false); // 模板下载loading
    const [daochuliebiaoLoading, setDaochuliebiaoLoading] = useState(false); // 导出列表loading
    const [carSheng, setCarSheng] = useState('陕'); // 省
    const [carShengShow, setCarShengShow] = useState(false); // 省弹窗显示与否
    const [pizhongValue, setPizhongValue] = useState<[ string, string ]>(); // 皮重
    const [maozhongValue, setMaozhongValue] = useState<[ string, string ]>(); // 毛重
    const contentValue: TablePaginationPosition = "bottomCenter";
    const [paging, setPaging] = useState({
        // 分页数据
        currentPage: 1,
        pageSize: 10,
    });
    const [daochuShow, setDaochuShow] = useState(false); // 导出设置弹窗显示与否
    //Tabs的items的内部表格组件
    const pagination = {
        //分页
        position: [contentValue],
        //是否可以改变pagesize//
        showSizeChanger: true,
        //是否可以快速跳转到某页
        showQuickJumper: true,
        //展示一共有多少条数据//
        showTotal: () => `共${totalValue}条`,
        //每页条数
        pageSize: paging.pageSize,
        //当前页数
        current: paging.currentPage,
        //数据总数
        total: totalValue,
        //页码改变的回调，参数是改变后的页码及每页条数
        onChange: (current: number, pageSize: number) => {
            setPaging({
                currentPage: current,
                pageSize: pageSize,
            });
        },
    };
    const ShengHtml = <ShengTanchaung>
        {
            licensePlateAbbreviations.map((item) => {
                return <div
                    key={item}
                    className={carSheng === item ? 'li-car active' : 'li-car'}
                    onClick={() => {
                        setCarSheng(item);
                    }}
                >
                    {item}
                </div>
            })
        }
    </ShengTanchaung>
    const selectAfter = (
        <div style={{ display: 'flex', alignItems: 'center' }}>
            <Select
                style={{ width: '6.6rem' }}
                value={prefix}
                onChange={(value) => {
                    setPrefix(value);
                }}
                options={[
                    { value: "蓝", label: "蓝" },
                    { value: "黄", label: "黄" },
                    { value: "绿", label: "绿" },
                    { value: "黑", label: "黑" },
                ]}>
            </Select>
            <Popover content={ShengHtml} trigger="click" onOpenChange={(open) => {
                setCarShengShow(open)
            }}>
                <ShengDiv>
                    <span style={{ color: !carShengShow ? 'rgba(0, 0, 0, 0.88)' : 'rgba(0, 0, 0, 0.45)' }} >{carSheng}</span><span className="iconfont" style={{ fontSize: '1.2rem', color: 'rgba(0, 0, 0, 0.88)' }}>&#xe661;</span>
                </ShengDiv>
            </Popover>
        </div>

    );

    const popoverContent = (arr: any[]) => {
        if (!arr) return <div>暂无数据</div>; // 如果 arr 是 null 或 undefined，返回 null

        return (
            <div>
                {arr.map((item, index) => (
                    <Button
                        key={index}
                        type="link"
                        onClick={() => handleNewUpload(item.url)}
                    >
                        <Tooltip title={item.fileName}>
                            {item.fileName.length < 10 ? item.fileName : item.fileName.substring(0, 7) + '...'}
                            
                            </Tooltip>
                    </Button>
                ))}
            </div>
        );
    };

    const handleNewUpload = (item: any) => {
        const link = document.createElement("a");
        link.href = item;
        link.target = '_blank';
        document.body.appendChild(link);
        link.click();
    }
    const columns: ColumnsType<IshipDetailType> = [
        {
            title: "序号",
            align: "center",
            width: useWindowFontSize(80),
            render: (text, record, index) => <span>{(paging.currentPage - 1) * paging.pageSize + index + 1}</span>
        },
        {
            title: "货品",
            align: "center",
            width: useWindowFontSize(80),
            dataIndex: "good",
        },
        {
            title: "车牌号",
            align: "center",
            width: useWindowFontSize(120),
            render: (text, record, index) => <span>{record.carColor}{record.carNum}</span>
        },
        {
            title: "一次计量重量(吨)",
            align: "center",
            width: useWindowFontSize(150),
            dataIndex: "pzWeight",
        },
        {
            title: "一次计量时间",
            align: "center",
            width: useWindowFontSize(180),
            dataIndex: "emptyTime",
        },
        {
            title: "一次计量拍照",
            align: "center",
            width: useWindowFontSize(120),
            render(value, record, index) {
                return (
                    <>
                        <Popover content={popoverContent(record.emptyPictures)} trigger="click">
                            <Button type="link" >查看图片</Button>
                        </Popover>
                    </>
                );
            },
        },
        {
            title: "一次计量视频",
            align: "center",
            width: useWindowFontSize(120),
            render(value, record, index) {
                return (
                    <>
                        <Popover content={popoverContent(record.emptyVideoFile)} trigger="click">
                            <Button type="link" >查看视频</Button>
                        </Popover>
                    </>
                );
            },
        },
        {
            title: "二次计量重量(吨)",
            align: "center",
            width: useWindowFontSize(150),
            dataIndex: "mzWeight",
        },
        {
            title: "二次计量时间",
            align: "center",
            width: useWindowFontSize(180),
            dataIndex: "weightTime",
        },
        {
            title: "二次计量拍照",
            align: "center",
            width: useWindowFontSize(120),
            render(value, record, index) {
                return (
                    <>
                        <Popover content={popoverContent(record.weightPictures)} trigger="click">
                            <Button type="link" >查看图片</Button>
                        </Popover>
                    </>
                );
            }
        },
        {
            title: "二次计量视频",
            align: "center",
            width: useWindowFontSize(120),
            render(value, record, index) {
                return (
                    <>
                        <Popover content={popoverContent(record.weightVideoFile)} trigger="click">
                            <Button type="link" >查看视频</Button>
                        </Popover>
                    </>
                );
            }
        },
        {
            title: "净重(吨)",
            align: "center",
            width: useWindowFontSize(100),
            dataIndex: "jzWeight",
        },
        {
            title: "过磅模式",
            align: "center",
            width: useWindowFontSize(100),
            dataIndex: "modelName",//过磅模式（0：自动过磅 1：脱机录入）
        },
    ]

    const onSearch = () => {
        const params = {
            ...paging,
            carNum: carSheng + searchValue,
            carColor: prefix,
            pzStartTime: pizhongValue ? pizhongValue[0] : undefined,
            pzEndTime: pizhongValue ? pizhongValue[1] : undefined,
            mzStartTime: maozhongValue ? maozhongValue[0] : undefined,
            mzEndTime: maozhongValue ? maozhongValue[1] : undefined,
        }
        listFun(params);
    }

    const props: UploadProps = {
        name: 'file',
        action: basicIp + '/gb-ship-form/importExcel',
        headers: {
            authorization: 'authorization-text',
            satoken: sessionStorage.getItem("token") as string
        },
        onChange(info) {
            if (info.file.status !== 'uploading') {
                console.log(info.file, info.fileList);
            }
            if (info.file.status === 'done') {
                message.success(`${info.file.name} 导入成功`);
                listFun({ ...paging });
            } else if (info.file.status === 'error') {
                message.error(`${info.file.name} 导入失败`);
            }
        },
    };


    const listFun = useCallback(async (params?: any) => {

        const { code, msg, data } = (await postShipDetail(params)) as IFenye<IshipDetailType>
        if (code === 20000) {
            setListData(data.records);
            settotalValue(data.total)

        } else {
            message.error(msg);
        }
    }, []);

    const hanldeCallback = () => {
        setAddShow(false);
        listFun({ ...paging });
    }

    const handleImport = () => {
        setDaochuliebiaoLoading(true);
        const token: string = sessionStorage.getItem("token") as string;
        axios({
            method: "post",
            url: basicIp + "/gb-ship-form/exportSend",
            data: { carNum: searchValue, carColor: prefix },
            //重要：相应类型必须为blob 
            responseType: "arraybuffer",
            headers: {
                satoken: token,
            },
        }).then((res) => {
            setDaochuliebiaoLoading(false);
            let contentDisposition = decodeURI(res.headers["content-disposition"]);
            let fileRegex = /([^(filename=)]+\.xlsx?)$/g;
            let result = contentDisposition.match(fileRegex)![0];
            var link = document.createElement("a");
            //将文件流信息传入
            link.href = window.URL.createObjectURL(new Blob([res.data]));
            link.download = result;
            link.click();
            window.URL.revokeObjectURL(link.href);
        }).catch(() => {
            setDaochuliebiaoLoading(false);
        });
    }

    useEffect(() => {
        listFun({ ...paging });
    }, [listFun, paging])

    return (
        <DataDetailBox>
            <div className="view-top">
                <div style={{height: '3.5rem', lineHeight: '3.5rem'}}>明细</div>
                <div >
                    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'flex-end', marginBottom: '2rem' }}> 
                        <span style={{ marginRight: '1rem'}}>车牌号</span>
                    <Input
                        // onSearch={onSearch}
                        value={searchValue}
                        onChange={(e) => { setSearchValue(e.target.value) }}
                        style={{ width: '30.3rem' }}
                        placeholder="请输入车牌号"
                        addonBefore={selectAfter}
                    />
                    <span style={{marginLeft: '2rem', marginRight: '1rem'}}>一次计量时间</span>
                    <RangePicker showTime style={{width: '40rem'}} value={pizhongValue ? [dayjs(pizhongValue[0]), dayjs(pizhongValue[1])] : undefined}  onChange={(dates, dateStrings) => {
                        console.log(dateStrings);
                        if(dateStrings[0] === '') {
                            setPizhongValue(undefined);
                            return;
                        }
                        setPizhongValue(dateStrings); 
                    }} />
                    <span style={{marginLeft: '2rem' , marginRight: '1rem'}}>二次计量时间</span>
                    <RangePicker showTime style={{width: '40rem'}} value={maozhongValue ? [dayjs(maozhongValue[0]), dayjs(maozhongValue[1])] : undefined}  onChange={(dates, dateStrings) => {
                          if(dateStrings[0] === '') {
                            setPizhongValue(undefined);
                            return;
                        }
                        setMaozhongValue(dateStrings); 
                    }} />
                    <Button type='primary' style={{marginLeft: '2rem'}} onClick={onSearch} >
                        查询
                    </Button>
                    <Button style={{marginLeft: '2rem'}} onClick={() => {
                        setCarSheng("陕");
                        setSearchValue("");
                        setPrefix("黄");
                        setPizhongValue(undefined);
                        setMaozhongValue(undefined);
                        setPaging({
                            currentPage: 1,
                            pageSize: 10,
                        })
                        listFun({
                            currentPage: 1,
                            pageSize: 10,
                        });
                    }}>
                        重置
                    </Button>
                    
                    </div>
                    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'flex-end' }}>
                        <Button icon={<PlusOutlined />} type="primary" onClick={() => {
                        setAddShow(true)
                    }}>
                        单次录入
                    </Button>
                    <Button
                    style={{marginLeft: '2rem'}}
                        icon={<DeliveredProcedureOutlined />}
                        onClick={() => {
                            setMobanxiazaiLoading(true);
                            gethandleTemplateDownload(
                                `${basicIp}/gb-ship-form/downloadTemplate`,
                                {
                                    fileName: "车辆档案模板",
                                },
                                "xlsx",
                                "arraybuffer",
                                () => {
                                    setMobanxiazaiLoading(false);
                                }
                            )
                        }}
                        loading={mobanxiazaiLoading}
                    >模板下载</Button>
                        <Upload
                            {...props}
                        >
                            {<Button
                            style={{marginLeft: '2rem'}}
                                icon={<ImportOutlined />}
                            >批量导入</Button>}
                        </Upload>
                        {/* <ExportOutlined /> */}
                        {<Button
                            onClick={handleImport}
                            icon={<ExportOutlined />}
                            style={{marginLeft: '2rem'}}
                            loading={daochuliebiaoLoading}
                        >导出列表</Button>}
                        {/* <ExportOutlined /> */}
                        {<Button
                            onClick={() => setDaochuShow(true)}
                            icon={<SettingOutlined />}
                            style={{marginLeft: '2rem'}}
                        >导出设置</Button>}
                    </div>
                   



                    
                </div>
            </div>
            <div style={{ padding: '1rem 2rem' }}>
                <ConfigProvider
                    theme={{
                        components: {
                            Table: {
                                headerColor: "#999999",
                                fontSize: useWindowFontSize(12),
                            },
                        },
                    }}
                >
                    <Table
                        columns={columns}
                        dataSource={listData}
                        pagination={pagination}
                        rowKey="id"
                        scroll={{ y: 500 }}
                    />
                </ConfigProvider>
            </div>
            <AddInfo
                AddCallBack={hanldeCallback}
                AddOpenShow={addShow}
            />
             {/* 导出设置 */}
             <DaochuSetModule
                isModalOpen={daochuShow}
                daochuSetModuleCallback={() => {
                    setDaochuShow(false);
                }}
             />
        </DataDetailBox>
    )
}

export default DataDetail;

